package org.tao.lightningmq.broker.netty.nameserver;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tao.lightningmq.broker.cache.CommonCache;
import org.tao.lightningmq.common.dto.HeartBeatDTO;
import org.tao.lightningmq.common.enums.NameServerEventCode;
import org.tao.lightningmq.common.enums.NameServerResponseCode;
import org.tao.lightningmq.common.remote.NameServerNettyRemoteClient;
import org.tao.lightningmq.common.tcp.TcpMsg;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author lht
 * @date 2025/1/8 - 17:23
 * @description:
 */
public class HeartBeatTaskManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatTaskManager.class);

    public void startHeartBeatTask() {
        new Thread(new HeartBeatRequestTask(), "heart-beat-request-task").start();
        LOGGER.debug("HeartBeatTaskManager startHeartBeatTask");
    }

    private static class HeartBeatRequestTask implements Runnable {
        @Override
        public void run() {
            NameServerClient nameServerClient = CommonCache.getNameServerClient();
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(3);
//                    NameServerNettyRemoteClient nameServerNettyRemoteClient = CommonCache.getNameServerClient().getNameServerNettyRemoteClient();
                    HeartBeatDTO heartBeatDTO = new HeartBeatDTO();
                    heartBeatDTO.setMsgId(UUID.randomUUID().toString());
                    TcpMsg tcpMsg = new TcpMsg(NameServerEventCode.HEART_BEAT.getCode(), JSON.toJSONBytes(heartBeatDTO));
                    nameServerClient.sendHeartBeatMsg(tcpMsg);
//                    TcpMsg heartBeatResp = nameServerNettyRemoteClient.sendSyncMsg(tcpMsg, heartBeatDTO.getMsgId());
//                    if (heartBeatResp.getCode() == NameServerResponseCode.HEART_BEAT_SUCCESS.getCode()) {
//                        if (LOGGER.isDebugEnabled()) {
//                            LOGGER.debug("heart beat ack from nameserver");
//                        }
//                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
